package com.hxy.basic.query.util;

import com.hxy.user.domain.LoginInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

/**
 * 封装获取登录上下文对象
 */
public class LoginContextUtil {

    /**
     * 获取登录上下文对象
     * @param request
     * @return
     */
    public static LoginInfo getLoginInfo(HttpServletRequest request){
        //1.想办法获取到容器对象：ApplicationContext
        //获取上下文对象
        ServletContext servletContext = request.getServletContext();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //2.调用getBean()获取对象,只要1.导入redis的依赖  2.配置  = Spring会自动管理RedisTemplate对象
        RedisTemplate redisTemplate = ac.getBean("redisTemplate",RedisTemplate.class);

        String token = request.getHeader("token");
        if(token != null){
            Object obj = redisTemplate.opsForValue().get(token);
            if(obj != null){
                return (LoginInfo) obj;
            }
        }
        return null;
    }
}
